﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;

namespace AspNetMvcTodo.IntegrationTests
{
    public class TestFixture : IDisposable
    {
        private readonly WebApplicationFactory<Program> _application;
        public HttpClient Client { get; }
        public IServiceProvider Services => _application.Services;

        public TestFixture()
        {
            _application = new WebApplicationFactory<Program>()
                .WithWebHostBuilder(builder => 
                {
                    builder.ConfigureAppConfiguration((context, config) =>
                    {
                        config.SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "..\\..\\..\\..\\AspNetMVCTodo"));
                        config.AddJsonFile("appsettings.json");

                    });

                    builder.UseEnvironment("Testing");

                    builder.ConfigureTestServices(services =>
                    {
                        // You can replace real services with fake ones here if needed
                        // services.AddScoped<ITodoItemService, FakeTodoItemService>();
                    });
                });
            var clientOptions = new WebApplicationFactoryClientOptions
            {
                AllowAutoRedirect = false       // 禁止自动重定向
            };

            Client = _application.CreateClient(clientOptions);
            Client.BaseAddress = new Uri("http://localhost:8888");
        }

        public void Dispose()
        {
            Client?.Dispose();
            _application?.Dispose();
            GC.SuppressFinalize(this);
        }
    }
}
